<template>
  <div class="community">
    <!-- 场所列表 -->
    <div class='add-community'>
      <el-button  type='primary' icon='el-icon-plus'  @click="handleInsert" class="function-btn" v-has-permission="btn[0]">新增场所</el-button>
    </div>
    <el-table :data='listData' stripe class='reg-tab' :header-cell-style="getRowClass" v-loading="loading">
      <el-table-column :prop="item.prop" :label="item.label" v-for="(item, index) in tableHead" :key="index"></el-table-column>
      <el-table-column label='操作' >
        <template slot-scope='scope'>
          <el-button type='text' size='small' @click="handleEdit(scope.row)" title="编辑" v-has-permission="btn[1]">
            <img src='../../../../../static/image/common/edit.png' alt=''></el-button>
          <el-button type='text' size='small' @click="handleView(scope.row)" title="查看" v-has-permission="btn[2]">
            <img src='../../../../../static/image/common/preview.png' alt=''></el-button>
          <el-button type='text' size='small' @click="handleDelete(scope.row)" title="删除" v-has-permission="btn[3]">
            <img src='../../../../../static/image/common/delete.png' alt=''></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--删除弹出框-->
    <delete-dialog :is-show="deleteDialogShow" :desc="desc" @close="handleClose"></delete-dialog>

    <div class="pagination">
      <div class='page-left'>
        <span>共{{ this.total}}条数据 </span>
        <span>每页:</span>
        <el-input placeholder="条数" v-model="inputs" @blur="pagesizeChange" @keyup.enter.native="pagesizeChange" clearable> </el-input>
        <span>条</span>
      </div>
      <el-pagination background layout="prev, pager, next, jumper"
                     :page-size="pageSize" :total="total"
                     @current-change="handleCurrentChanges" id='page' :current-page.sync="currentPage">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import Config from '../../../../config'
  import DeleteDialog from '../../../../components/CommonDialog'
  import {regionDataPlus} from 'static/js/regionData'
  import { mapGetters } from 'vuex'
  export default {
    name: 'Community',
    components: {
      DeleteDialog
    },
    props: {
      btn: {
        type: Array
      }
    },
    data () {
      return {
        tableHead: [
          {prop: 'site_serialno', label: '序号'},
          {prop: 'site_name', label: '场所名称'},
          {prop: 'areaName', label: '区域名称'},
          {prop: 'address', label: '详细地址'}
        ],
        // 表格数据
        listData: [
          { site_serialno: '1', areaName: '长安区', site_name: '雅居乐', address: '书院路', }
        ],
        // 弹出框
        dialogVisible: false,
        // 是否预览
        isView: false,
        title: '',
        COMMUNITY_INSERT: '新增场所',
        COMMUNITY_EDIT: '场所编辑',
        COMMUNITY_VIEW: '场所预览',
        communityForm: {
          username: '',
          realname: '',
          phone: '',
          role: '',
          area: '',
          signtime: ''
        },
        // 查询
        searchForm: {
          username: '',
          role: 'all',
          signtime: null
        },
        roleEnum: [
          {
            name: '全部',
            id: 'all'
          }
        ],
        // 分页
        total: 1,
        currentPage: 1,
        pageSize: 15,
        inputs:15,
        // loading
        loading: false,
        // 删除对象
        deleteObject: null,
        deleteDialogShow: false,
        desc: ''
      }
    },
    computed: {
      ...mapGetters('user', {
        district: 'getDistrict',
        user: 'getUser'
      })
    },
    mounted () {
      this.getCommunity()
    },
    methods: {
      /**
       * 当前页变化
       * */
      handleCurrentChanges(val) {
        this.currentPage = val
        this.getCommunity();
      },
      /**
       * 每页大小变化
       * */
      pagesizeChange () {
        if (+this.inputs === 0) {
          this.inputs = 15
        }
        if (Number.isInteger(+this.inputs)) {
          this.pageSize = +this.inputs
          this.getCommunity()
        } else {
          this.$message({
            message: '请输入整数',
            type: 'warning'
          })
        }
      },
      /**
       * 从后台获取人员列表
       * */
      getCommunity () {
        const url = `${Config.DEVICE_MANAGE_URL}/final_equipsite/query`
        let param = {
          page: this.currentPage - 1,
          size: this.pageSize,
          site_info: 'real' // 过滤掉烟感c端创建的场所
        }
        param = this.preHandleParam(param)
        console.log(param)
        this.$http.get(url, param)
          .then(data => {
            const list = data.array
            this.listData.splice(0)
            list.forEach(item => {
              this.handleData(item)
              this.listData.push(item)
            })
            this.total = data.allcount
          })
      },
      /**
       * 预处理查询参数
       * @param {JSON} param
       * */
      preHandleParam (param) {
        const province = this.district.provinceCode || ''
        const city = this.district.cityCode || ''
        const district = this.district.areaCode || ''
        const id = this.district.districtId || ''
        if (district) { // 包含区编码,角色为场所管理员
          if (id) {
            param = {...param, ...{id}}
          }
        } else {
          if (city) { // 包含市编码
            param = {...param, ...{city}}
          } else {
            if (province) { // 包含省编码
              param = {...param, ...{province}}
            }
          }
        }
        return param
      },
      /**
       * 对展示数据进行预处理
       * */
      handleData (item) {
        const province = this.getAreaObj(regionDataPlus, item.province)
        const city = this.getAreaObj(province.children, item.city)
        const district = item.district ? this.getAreaObj(city.children, item.district) : {label: ''}
        item.areaName = `${province.label}${city.label}${district.label}`
      },
      /**
       * 获取区域信息
       * @param {Array} arr
       * @param {String} value
       * @return {Object} obj
       * */
      getAreaObj (arr, value) {
        let obj = null
        arr.some(item => {
          if (value === item.value) {
            obj = item
            return true
          }
        })
        return obj
      },
      /**
       * 表头添加背景颜色
       * */
      getRowClass({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background:#fafbfc'
        } else {
          return ''
        }
      },
      /**
       * 新增场所
       * */
      handleInsert() {
        this.title = this.COMMUNITY_INSERT
        this.$router.push({
          path: `/system/info/community/create`
        })
      },
      /**
       * 编辑场所
       * */
      handleEdit (row) {
        this.title = this.COMMUNITY_EDIT
        this.$router.push({
          path: `/system/info/community/edit/${row.site_serialno}-${row.district}`
        })
      },
      /**
       * 场所预览
       * */
      handleView (row) {
        this.title = this.COMMUNITY_VIEW
        console.log(row)
        this.$router.push({
          path: `/system/info/community/view/${row.site_serialno}-${row.district}`
        })
      },
      /**
       * 删除场所
       * */
        // 删除限制数量

      handleDelete(row) {
        let url = `${Config.DEVICE_MANAGE_URL}/device_modify_history/count_by_action_imei`;
        let param = {
          user_id: this.user.id,
          action_name:'delete_site'
        };
        this.$http.get(url,param).then(res =>{
        // console.log(res)
        if(res.count <= 20){
          this.deleteObject = row
          this.desc = `确定要删除${row.site_name}吗？`
          this.deleteDialogShow = true
        }else{
          this.$message({
            message: "您已删除超过20个设备,已通知主运营公司管理员,如需删除设备，请于明天再进行删除操作。",
            type: "error"
          })
        }
      })


      },
      handleClose (id) {
        this.deleteDialogShow = false
        if (!id) {
          this.deleteObject = null
          return
        }
        const user = this.user
        const url = `${Config.DEVICE_MANAGE_URL}/final_equipsite/delete`
        const params = {
          id: this.deleteObject.id,
          login_name: user.loginName,
          user_id: user.id
        }
        this.$http.post(url, params)
          .then(data => {
            this.deleteObject = null
            this.$message.success('删除成功')
            // 重新拉场所数据
            this.currentPage = 1
            this.pageSize = 15
            this.getCommunity()
          })
          .catch(e => {
            this.deleteObject = null
            this.$message.error(e.message)
          })
      },
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../../../../static/scss/common";
  .community {
    width: 100%;
    height: auto;
    background: $white;
    .add-community {
      height: 28px;
      margin-right: 27px;
      text-align: right;
    }
    .pagination{
      padding: 32px 0 44px 23px;
      .page-left{
        font-size: 12px;
        display: inline-block;
        .el-input--suffix{
          width: 56px;
        }
      }
    }
  }
</style>
